// pages/goodsDetail/goodsDetail.js
var httpUtil = require('../../utils/httpUtil.js');
var area = require('../../utils/area.js')
var areaInfo = []; //所有省市区县数据
var provinces = [];
var citys = [];
var countys = [];
var index = [0, 0, 0];
var t = 0;
var show = false;
var moveY = 200;

Page({

  /**
   * 页面的初始数据
   */
  data: {
    couponid:'',
    contents:'',
    name: '',
    phone: '',
    address: '',
    province: '',
    city: '',
    region: '',
    num: 1, //数量
    price: '',
    nowprice: 0, //现价
    total_price: 0, //总价
    del_price: 0, //抵现
    goodid: '',
    list1: [],

    show: show,
    provinces: '',
    citys: '',
    countys: '',
    value: [0, 0, 0]
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var that = this;
    //获取省市区县数据
    area.getAreaInfo(function(arr) {
      areaInfo = arr;
      //获取省份数据
      getProvinceData(that);
    });
   
    if (wx.getStorageSync('addressId') == '') {
      that.setData({
        name: '',
        phone: '',
        address: '',
      })
      return;
    }
  },
  //获取默认地址
  myaddress: function () {
    var that = this;
    var req = {
      token: wx.getStorageSync('token'),
      userid: wx.getStorageSync('userId')
    }
    httpUtil.post("/crm/usershopaddresslist", req)
      .then(function (res) {
        for (var i = 0; i < res.data.data.msg.length; i++) {
          if (res.data.data.msg[i].isdefault == '是') {
            var req = {
              id: res.data.data.msg[i].id
            }
            httpUtil.post("/crm/usershopaddressinfo", req)
              .then(function (res) {
                if (res.data.status == 200) {
                  that.setData({
                    name: res.data.data.truename,
                    phone: res.data.data.phone,
                    address: res.data.data.address,
                    province: res.data.data.province,
                    city: res.data.data.city,
                    region: res.data.data.region,
                    isdefault: res.data.data.isdefault,
                  })

                } else {
                  wx.showToast({
                    title: '' + res.data.message + '',
                  })
                }
              }).catch(function (res) {
                console.log(res);
              });
          }
        }
      }).catch(function (res) {
        console.log(res);
      });
  },
  // 获取我的优惠券
  mycoupon: function() {
    var that = this;
    var pages = getCurrentPages()
    var page = pages[pages.length - 2]
    that.setData({
      num:  page.data.num,
      nowprice:  page.data.nowprice,
      goodid: page.data.goodid,
      total_price: (page.data.nowprice * page.data.num)
    });

    var req = {
      money: that.data.total_price,
      userid: wx.getStorageSync('userId')
    }
    httpUtil.post("/crm/usercoupon", req)
      .then(function(res) {

        if (res.data.status == 200) {
          var arr = [];
          for (var i = 0; i < res.data.data.length; i++) {
            arr.push(res.data.data[i])
            if (res.data.data[i].choose == true) {
              console.log('147', res.data.data[i].jian)
              that.setData({
                couponid: res.data.data[i].couponid,
                del_price: res.data.data[i].jian,
                total_price: that.data.total_price - res.data.data[i].jian,
              })

            }
          }

          that.setData({
            list1: arr,
          })
        }
      }).catch(function(res) {
        console.log(res);
      });
  },
  // ------------------- 分割线 --------------------
  onReady: function() {
    this.animation = wx.createAnimation({
      transformOrigin: "50% 50%",
      duration: 0,
      timingFunction: "ease",
      delay: 0
    })
    this.animation.translateY(200 + 'vh').step();
    this.setData({
      animation: this.animation.export(),
      show: show
    })
  },
  //滑动事件
  bindChange: function(e) {
    var val = e.detail.value
    //判断滑动的是第几个column
    //若省份column做了滑动则定位到地级市和区县第一位
    if (index[0] != val[0]) {
      val[1] = 0;
      val[2] = 0;
      getCityArr(val[0], this); //获取地级市数据
      getCountyInfo(val[0], val[1], this); //获取区县数据
    } else { //若省份column未做滑动，地级市做了滑动则定位区县第一位
      if (index[1] != val[1]) {
        val[2] = 0;
        getCountyInfo(val[0], val[1], this); //获取区县数据
      }
    }
    index = val;
    //更新数据
    this.setData({
      value: [val[0], val[1], val[2]],
      province: provinces[val[0]].text,
      city: citys[val[1]].text,
      region: countys[val[2]].text
    })

  },
  //移动按钮点击事件
  translate: function(e) {
    if (t == 0) {
      moveY = 0;
      show = false;
      t = 1;
    } else {
      moveY = 200;
      show = true;
      t = 0;
    }
    animationEvents(this, moveY, show);

  },
  //隐藏弹窗浮层
  hiddenFloatView(e) {
    moveY = 200;
    show = true;
    t = 0;
    animationEvents(this, moveY, show);

  },
  formName: function(e) {
    this.setData({
      name: e.detail.value
    })
  },
  formphone: function(e) {
    this.setData({
      phone: e.detail.value
    })
  },
  formaddress: function(e) {
    this.setData({
      address: e.detail.value
    })
  },
  formcontents: function (e) {
    this.setData({
      contents: e.detail.value
    })
  },
  //支付
  buy: function() {
    var that = this;
    //正则匹配
    var mobile = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
    // var myreg = /^(([0\+]\d{2,3}-)?(0\d{2,3})-)(\d{7,8})(-(\d{3,}))?$/;  //判断是否是座机电话
    var isMobile = mobile.exec(that.data.phone)
    if (that.data.name == '' || that.data.phone == '' || that.data.address == '') {
      wx.showModal({
        title: '提示!!!',
        content: '请完整填写信息',
      })
    } else if (!isMobile) {
      wx.showModal({
        title: '提示!!!',
        content: '你输入的电话不符，请重新检查填写',
      })
    } else {
      var req = {
        token: wx.getStorageSync("token"),
        num: that.data.num,
        userid: wx.getStorageSync('userId'),
        DevID: wx.getStorageSync('deviceid'),
        openid: wx.getStorageSync("openId"),
        goodid: that.data.goodid,
        truename: that.data.name,
        phone: that.data.phone,
        province: that.data.province,
        city: that.data.city,
        region: that.data.region,
        address: that.data.address,
        contents: that.data.contents,
        couponid: that.data.couponid,        
      }
      // 添加订单的接口
      httpUtil.post("/crm/goodwxpay", req)
        .then(function(res){
          //微信支付
          wx.requestPayment({
            timeStamp: res.data.timeStamp, //时间戳 当前的时间
            nonceStr: res.data.nonceStr, //随机字符串
            package: res.data.package,
            signType: res.data.signType,
            paySign: res.data.paySign,
            //接口调用成功
            'success': function(res) {
              //打开设备
              wx.showToast({
                title: '购买成功,等待卖家发货。。。',
                icon: 'none',
                duration: 2000,
              })
            },
            //接口调用失败
            'fail': function(res) {
              console.log(res)
              if (res == 'requestPayment:fail cancel') {
                return;
              }
              //用户取消或支付异常
            },
            //接口调用结束
            'complete': function(res) {

            }
          })
        }).catch(function(res) {
          console.log(res);
        });

    }
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    var that = this;
    //获取当前网络状态
    wx.getNetworkType({
      success: function(res) {
        // 返回网络类型, 有效值：
        // wifi/2g/3g/4g/unknown(Android下不常见的网络类型)/none(无网络)
        if (res.networkType == 'none' || res.networkType == 'unknown') {
          that.setData({
            outline: true,
          })
        } else {
          that.setData({
            outline: false,
          })
          that.mycoupon(),
            that.myaddress()
        }
      }
    })

    //监听网络状态
    wx.onNetworkStatusChange(function(res) {
      if (res.networkType == 'none' || res.networkType == 'unknown') {
        that.setData({
          outline: true
        })
      } else {
        that.setData({
          outline: false,
        })
        that.mycoupon(),
        that.myaddress()

      }
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    wx.stopPullDownRefresh()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }

})

// ---------------- 分割线 ----------------
//动画事件
function animationEvents(that, moveY, show) {
  console.log("moveY:" + moveY + "\nshow:" + show);
  that.animation = wx.createAnimation({
    transformOrigin: "50% 50%",
    duration: 400,
    timingFunction: "ease",
    delay: 0
  })
  that.animation.translateY(moveY + 'vh').step()

  that.setData({
    animation: that.animation.export(),
    show: show
  })
}

//获取省份数据
function getProvinceData(that) {
  var num = 0;
  for (var i = 0; i < areaInfo.length; i++) {
    provinces[num] = areaInfo[i];
    num++;
  }
  that.setData({
    provinces: provinces
  })
  //初始化调一次可更改
  getCityArr(0, that);
  getCountyInfo(0, 0, that);
  that.setData({
    province: "北京市",
    city: "北京市",
    region: "东城区",
  })

}
// 获取地级市数据
function getCityArr(count, that) {
  var num = 0;
  for (var i = 0; i < provinces[count].children.length; i++) {
    citys[num] = provinces[count].children[i]
    num++;
  }
  if (citys.length == 0) {
    citys[0] = {
      name: ''
    };
  }
  that.setData({
    city: "",
    citys: citys,
    value: [count, 0, 0]
  })
}
// 获取区县数据
function getCountyInfo(column0, column1, that) {
  var num = 0;
  for (var i = 0; i < citys[column1].children.length; i++) {
    countys[num] = citys[column1].children[i]
    num++;
  }
  if (countys.length == 0) {
    countys[0] = {
      name: ''
    };
  }
  that.setData({
    region: "",
    countys: countys,
    value: [column0, column1, 0]
  })
}